package com.sdgakj.web.family;

import com.google.common.collect.Maps;
import com.sdgakj.entity.Family;
import com.sdgakj.entity.Person;
import com.sdgakj.service.account.ShiroDbRealm;
import com.sdgakj.service.family.FamilyService;
import com.sdgakj.service.person.PersonService;
import com.sdgakj.service.user.UserService;
import com.sdgakj.utils.DateUtil;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

@Controller
@RequestMapping(value = "/familytree")
public class FamilyTreeController {

    private static Logger logger = LoggerFactory.getLogger(FamilyTreeController.class);

    @Autowired
    private FamilyService familyService;
    @Autowired
    private PersonService personService;

    private static final String PAGE_SIZE = "10";

    private static Map<String, String> sortTypes = Maps.newLinkedHashMap();

    static {
        sortTypes.put("auto", "自动");
    }

    /**
     * 跳转到家族树界面treeMessage
     *
     * @return
     */
    @RequestMapping(value = "/ftree", method = RequestMethod.GET)
    public String toFamilyTree() {
        return "family/familytreeList";
    }

    /**
     * 加载家族树json
     *
     * @return
     */
    @RequestMapping(value = "/treeMessage")
    @ResponseBody
    public Map<String, Object> treeMessage() {
        Map<String, Object> map = new HashMap<>();
        //当前家族中的所有person数据
        ShiroDbRealm.ShiroUser shiroUser = (ShiroDbRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
        Long id = shiroUser.id;//用户id
        Family family = familyService.getFamilyByUserId(id);
        Long familyId = family.getId();//家族id;
        //查询这个家族的所有成员
        List<Person> personList = personService.getPersonsByFId(familyId);
        HashMap<Long, Person> personMap = new HashMap<>();
        for (Person person : personList) {
            personMap.put(person.getId(), person);
        }
        map.put("nodes", personMap);
        //当前家族中的所有关系数据
        map.put("root_id", id);
        return map;
    }


    /**
     * 跳转到添加家族树界面
     * @return
     */
    @RequestMapping("/toAddPerson")
    public String toAddPerson() {
        return "/family/familyTreeForm";
    }

    /**
     * 添加家族成员
     * 在孩子的基础上，世系加1
     * @param person
     * @param model
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public String createPerson(Person person,
                               @RequestParam("borntime") String borntime,
                               @RequestParam("spouseid") Long spouseid,//配偶id
                               @RequestParam("childid") Long childid,//子女id
                               @RequestParam("familyid") Long familyid,//所属家族id
                               Model model) {
        //转换日期数据
        Date date = DateUtil.formatStringToDate(borntime, "yyyy-MM-dd HH:mm:ss");
        person.setBornTime(date.toString());

        person.setAlive(1);//默认添加是在世
        person.setChildNumber(1);//第一次添加只能有1个孩子 TODO: 如果是添加兄弟的话，要改动父母的孩子和关系表
/*
        person.setBindUser(0);//默认未关联用户
*/
        person.setCreatetime(DateUtil.getDate());
        person.setUpdatetime(DateUtil.getDate());
//        person.setUser(null);//数据库默认是null
        //世系+1
        if (childid!=null){
            Person child = personService.getPersonById(Long.valueOf(childid));
            person.setGeneration(child.getGeneration() + 1);
        }
        //计算年龄
        // TODO: 改成前台动态计算，不能写死
       /*int age = DateUtil.getAge(borntime, "yyyy-MM-dd");
        person.setAge(String.valueOf(age));*/
        //判断是否已婚
        if (spouseid == null) {//没有配偶，未婚
            person.setMarry(0);
        } else {//有配偶 已婚
            person.setMarry(1);//已婚
        }
        //保存person信息，返回该对象的id
        Long saveId = personService.savePerson(person);

        //添加人员关系
        //添加跟孩子的关系
        Family family = new Family(familyid);
        //如果有配偶，就添加配偶关系
        return "family/familytreeList";
    }
}
